// 获取歌曲详情派发出新数据

import {
  getsongUrl,
  getMusicLyc,
  getSongsComment
} from "@/request/api.js";



export default class Song {
  constructor({
    id,
    mid,
    singer,
    name,
    album,
    duration,
    image,
    url,
    vip,
  }) {
    this.id = id;
    this.mid = mid;
    this.singer = singer;
    this.name = name;
    this.album = album;
    this.duration = duration;
    this.image = image;
    this.url = `https://music.163.com/song/media/outer/url?id=${this.id}.mp3`;
    this.like = false
  }
  getLyc() {
    if (this.lyric) {
      return Promise.resolve(this.lyric)
    }
    return new Promise((resolve, reject) => {
      getMusicLyc(this.id).then((res) => {
        console.log(res);
        if (res.code === 200) {
          // 抛出返回的歌词：
          if (!res.nolyric) {
            resolve(res.lrc.lyric)
          } else {
            reject('获取歌词失败')
          }
        } else {
          reject('获取歌词失败')
        }
      })
    })
  }
  getComment() {
    if (this.comment) {
      return Promise.resolve(this.comment)
    }
    return new Promise((resolve, reject) => {
      getSongsComment(this.id).then((res) => {
        console.log(res);
        if (res.code === 200) {
          resolve(res)
        } else {
          reject('获取评论失败')
        }
      })
    })
  }
  checkVip() {
    getsongUrl({
      id: this.id
    }).then(res => {
      if (res.data[0].url) {
        this.vip = false
      } else {
        this.vip = true
      }
    })
  }
}

export function createSong(musicData) {
  return new Song({
    id: musicData.id,
    mid: musicData.al.id,
    singer: filterSinger(musicData.ar),
    duration: musicData.duration ? musicData.duration / 1000 : musicData.dt ? musicData.dt / 1000 : '',
    name: musicData.name,
    album: musicData.al.name,
    image: musicData.al.picUrl + '?param=300y300',
    url: musicData.id,
    like: musicData.like ? musicData.like : false
  });
}

export function createSearchSongs(musicData) {
  return new Song({
    id: musicData.id,
    mid: musicData.album.id,
    singer: filterSinger(musicData.artists),
    duration: musicData.duration ? musicData.duration / 1000 : musicData.dt ? musicData.dt / 1000 : '',
    name: musicData.name,
    album: musicData.album.name,
    image: musicData.picUrl ? musicData.picUrl : musicData.album.artist.img1v1Url + '?param=300y300',
    url: musicData.id,
  });
}

export function filterSinger(singer) {
  let ret = [];
  if (!singer) {
    return ''
  }
  singer.forEach((s) => {
    ret.push(s.name)
  })
  return ret.join('/')
}
